package matrix;


import java.awt.event.ActionListener;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableModel;
import org.jvnet.substance.skin.SubstanceSaharaLookAndFeel;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * testMatrix.java
 *
 * Created on Jan 21, 2014, 4:29:08 PM
 */

/**
 *
 * @author Daniel Huynh
 */
public class testMatrix extends javax.swing.JFrame {

    private float y = 1;
    Vector data = new Vector();
    Vector<String> header = new Vector<String>();
    Vector data2 = new Vector();
    private float[][] arr = new float[20][20];
    DefaultTableModel defaultModel;
    /** Creates new form testMatrix */
    public testMatrix() {
        initComponents();
        //matrix A
        defaultModel = (DefaultTableModel)tblA.getModel();
        defaultModel.setDataVector(data,header);
        //matrix result
        defaultModel = (DefaultTableModel)tblB.getModel();
        defaultModel.setDataVector(data2, header);
        setLocationRelativeTo(null);
    }
    public void ySetter(float y) {
        this.y = y;
    }
    private int GetRow() {
        String row = this.txtRow.getText().trim();
        int row1 = Integer.parseInt(row);
        return row1;
    }
    private int GetCol() {
        String col = this.txtCol.getText().trim();
        int col1 = Integer.parseInt(col);
        return col1;
    }

    // get data to array
    private void GetData() {
        for (int i = 0; i < GetRow(); i++) {
            for (int j = 0; j < GetCol(); j++) {
                arr[i][j] = Integer.parseInt((String)this.tblA.getValueAt(i, j));
            }
        }
        if (GetCol() == GetRow()) {
        for (int i = 0; i < GetCol(); i++) {
                for (int j = 0; j < GetCol(); j++) {
                    arr[i][j + GetCol()] = 0;
                    arr[i][i + GetRow()] = 1;
                }
            }
        }
    }
    //check if it is the square martrix
    private boolean SquareMatrix() {
        if (GetCol() == GetRow()) {
            return true;
        }
        return false;
    }
    // calculate determinant
    private float Detm () {
        Gauss();
            float res = 1;
            for (int i = 0; i < GetCol(); i++) {
                res = res*arr[i][i];
            }
            return res*y;
    }

    // calculate determinant
    private void Gauss() {
        GetData();
            for (int i = 0; i < GetRow() - 1; i++) {
                if (arr[i][i] == 0) { // change the position to make arri[i][i] # 0
                for (int x = i; x < GetRow(); x++) {
                    for (int j = i; j < GetCol(); j++) {
                        if(arr[x][j] !=0) {
                            for (int k = 0; k < 2*GetCol(); k++) {
                                float[][] temp = new float[10][10];
                                temp[0][k] = arr[i][k];
                                arr[i][k] = arr[x][k];
                                arr[x][k] = temp[0][k];
                            }
                            for (int k = 0; k < GetRow(); k++) {
                                float[][] temp = new float[10][10];
                                temp[0][k] = arr[k][i];
                                arr[k][i] = arr[k][j];
                                arr[k][j] = temp[0][k];
                            }
                            break;
                        }
                    }
                }
            }
                y = y*arr[i][i]; // y to calculate the determinant
                for (int x = 2*GetCol() - 1; x >= 0; x--) {
                    if (arr[i][i] != 0 && arr[i][i] != 1) {
                        arr[i][x] = arr[i][x]/arr[i][i];
                    }
                    else break;
                }
                for (int j = i; j < GetRow(); j++) {
                    for (int k = 2*GetCol() - 1; k >= 0; k--) {
                        arr[j+1][k] = -arr[i][k]*arr[j+1][i] + arr[j+1][k];
                    }
                }
            }
    }

    // continue Gauss() to calculate invert matrix
    //calculate invert matrix
    private void GaussInvert() {
        float res = Detm();
        if (res != 0) {
            GetData();
           Gauss();
           for (int i = 2*GetCol() - 1; i >= 0; i--) {
                    arr[GetRow() - 1][i] = arr[GetRow() - 1][i] / arr[GetRow() - 1][GetCol() - 1];
                }
            for (int i = GetCol() - 1; i > 0; i--) {
                 for (int j = i; j > 0; j--) {
                        for (int k = 2*GetCol() - 1; k >= 0; k--) {
                            arr[j-1][k] = -arr[i][k]*arr[j-1][i] + arr[j-1][k];
                        }
                    }
            }
        }
        else JOptionPane.showMessageDialog(null, "Dont have invert matrix because DetA=0");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblA = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtRow = new javax.swing.JTextField();
        txtCol = new javax.swing.JTextField();
        btnGet = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        btnDet = new javax.swing.JButton();
        txtDet = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblB = new javax.swing.JTable();
        btnInvert = new javax.swing.JButton();
        btnEche = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblA.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblA.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblAMouseClicked(evt);
            }
        });
        tblA.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tblAKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(tblA);

        jLabel1.setText("A");

        jLabel3.setText("Row:");

        jLabel4.setText("Col:");

        txtRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRowActionPerformed(evt);
            }
        });

        btnGet.setText("Get");
        btnGet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGetActionPerformed(evt);
            }
        });

        btnNew.setText("New");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Determinant"));

        btnDet.setText("Determinant");
        btnDet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetActionPerformed(evt);
            }
        });

        txtDet.setEditable(false);
        txtDet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDetActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnDet)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(txtDet, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnDet)
                .addGap(26, 26, 26)
                .addComponent(txtDet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        tblB.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tblB);

        btnInvert.setText("Invert Matrix");
        btnInvert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInvertActionPerformed(evt);
            }
        });

        btnEche.setText("Row-Echelon");
        btnEche.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEcheActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(45, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEche)
                    .addComponent(btnInvert))
                .addGap(42, 42, 42))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnInvert)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(btnEche)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(101, 101, 101)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtCol)
                            .addComponent(txtRow, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnGet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnNew, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3)
                                    .addComponent(txtRow, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnGet))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtCol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel4)
                                    .addComponent(btnNew))
                                .addGap(20, 20, 20))))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRowActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_txtRowActionPerformed

    private void btnGetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGetActionPerformed
        // TODO add your handling code here:
        data.removeAllElements();
        header.removeAllElements();
        for (int i = 0; i < GetCol(); i++) {
            header.add("");
        }
        for (int i = 0; i < GetRow(); i++) {
            Vector v = new Vector ();
        for (int j = 0; j < GetCol(); j++) {
            v.add("");
        }
        data.add(v);
        }
        defaultModel = (DefaultTableModel)tblA.getModel();
        defaultModel.setDataVector(data,header);
        this.tblA.updateUI();
    }//GEN-LAST:event_btnGetActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
            this.txtCol.setText("");
            this.txtRow.setText("");
            this.txtDet.setText("");
            ySetter(1);
            data.removeAllElements();
            header.removeAllElements();
            tblA.updateUI();
            data2.removeAllElements();
            header.removeAllElements();
            tblB.updateUI();
    }//GEN-LAST:event_btnNewActionPerformed

    private void tblAMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAMouseClicked
        // TODO add your handling code here:
        int pos = this.tblA.getSelectedRow();
      //  this.tblA.setValueAt(data, pos, pos);
    }//GEN-LAST:event_tblAMouseClicked

    private void tblAKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblAKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_tblAKeyTyped

    private void btnDetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetActionPerformed
        // TODO add your handling code here:
        if (SquareMatrix()) {
            float res;
            res = Detm();
            if (res == 0) this.txtDet.setText("0");
            else {
                //cach chuyen kieu float sang String
            String st = String.format("%.2f", res);
            this.txtDet.setText(st);
            }
        }
        else {
            JOptionPane.showMessageDialog(null, "Error!! The matrix is not square");
        }
    }//GEN-LAST:event_btnDetActionPerformed

    private void txtDetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDetActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDetActionPerformed

    private void btnEcheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEcheActionPerformed
        // TODO add your handling code here:
        data2.removeAllElements();
        header.removeAllElements();
        Gauss();
        for (int i = 0; i < GetCol(); i++) {
            header.add("");
        }
        for (int i = 0; i < GetRow(); i++) {
            Vector v = new Vector ();
        for (int j = 0; j < GetCol(); j++) {
            v.add(arr[i][j]);
        }
        data2.add(v);
        }
        defaultModel = (DefaultTableModel)tblB.getModel();
        defaultModel.setDataVector(data2,header);
        this.tblB.updateUI();
    }//GEN-LAST:event_btnEcheActionPerformed

    private void btnInvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInvertActionPerformed
        // TODO add your handling code here:
        data2.removeAllElements();
        header.removeAllElements();
        if (SquareMatrix()) {
                GaussInvert();
                for (int i = 0; i < GetCol(); i++) {
                header.add("");
                }
                for (int i = 0; i < GetRow(); i++) {
                Vector v = new Vector ();
                for (int j = GetCol(); j < 2*GetCol(); j++) {
                    v.add(arr[i][j]);
                }
                data2.add(v);
                }
                defaultModel = (DefaultTableModel)tblB.getModel();
                defaultModel.setDataVector(data2,header);
               
               // btnInvert.setEnabled(false);
            }
        else {
            JOptionPane.showMessageDialog(null, "Error!! The matrix is not square");
        }
    }//GEN-LAST:event_btnInvertActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                setDefaultLookAndFeelDecorated(true);
                try {
                    UIManager.setLookAndFeel(new SubstanceSaharaLookAndFeel());
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(testMatrix.class.getName()).log(Level.SEVERE, null, ex);
                }
                new testMatrix().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDet;
    private javax.swing.JButton btnEche;
    private javax.swing.JButton btnGet;
    private javax.swing.JButton btnInvert;
    private javax.swing.JButton btnNew;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblA;
    private javax.swing.JTable tblB;
    private javax.swing.JTextField txtCol;
    private javax.swing.JTextField txtDet;
    private javax.swing.JTextField txtRow;
    // End of variables declaration//GEN-END:variables

}
